﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace JobColler.util
{
    class HttpUtils
    {
        public static string request(string url, string method, string pdata, string renEncode)
        {
            string srcString = "";
            byte[] postData = new ASCIIEncoding().GetBytes(pdata);
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);  //创建httpwebrequest对象
                request.Method = method.ToUpper();
                request.KeepAlive = true;
                request.ContentLength = postData.Length;
                request.AllowAutoRedirect = true;
                request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                request.UserAgent = "Mozilla/5.0 (compatible; Baiduspider/2.0; http://www.baidu.com/search/spider.html)";
                request.ContentType = "application/x-www-form-urlencoded";
                request.Headers.Add("Accept-Language", "zh-cn");
                request.Referer = url;
                request.MaximumAutomaticRedirections = 5;
                request.Timeout = 15 * 1000;
                HttpWebResponse response; //判断提交方式
                if (method.ToUpper() == "POST")
                {
                    Stream outputStream = request.GetRequestStream();
                    outputStream.Write(postData, 0, postData.Length);
                    outputStream.Close();
                }
                Stream responseStream;
                StreamReader reader;
                response = (HttpWebResponse)request.GetResponse();
                if ((int)(response.StatusCode) == 200)
                {
                    responseStream = response.GetResponseStream();
                    reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding(renEncode.ToUpper()));
                    srcString = reader.ReadToEnd();  //返回值赋值
                    reader.Close();
                    response.Close();
                }
            }
            catch { }
            return srcString;
        }
    }
}
